using System;
using System.Data;
using System.Data.Common;
using System.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.OleDb;


namespace Tilver.DBConnectionUI.Editors
{
    [ToolboxItem(false)]
    internal partial class OleDbAccessEditor : UserControl,IUDLEditor, IOleDbEditor
	{
        OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();

        public OleDbAccessEditor()
		{
			InitializeComponent();

            this.txDataSource.Validated += delegate { this.SetValue("Data Source", this.txDataSource.Text); };
            this.txUserID.Validated += delegate { this.SetValue("User Id", this.txUserID.Text); };
            this.txPassword.Validated += delegate { this.SetValue("Password", this.txPassword.Text); };
            this.ckPersistSecurityInfo.CheckedChanged += delegate { this.SetValue("Persist Security Info", this.ckPersistSecurityInfo.Checked); };

        }

        #region IConnectionEditor Members

        public string ConnectionString
        {
            get
            {
                return builder.ConnectionString;
            }
            set
            {
                try
                {
                    builder.ConnectionString = value;
                }
                catch (Exception) { }
                this.RefreshData();
            }
        }

        public void RefreshData()
        {
            this.txDataSource.Text = Convert.ToString(GetValue("Data Source"));
            this.txUserID.Text = Convert.ToString(GetValue("User Id"));
            this.txPassword.Text = Convert.ToString(GetValue("Password"));
            this.ckPersistSecurityInfo.Checked = Convert.ToBoolean(this.GetValue("Persist Security Info"));

        }

        public object GetAdvancedPropertiesObject()
        {
            ObjectWrapper wrapper = new ObjectWrapper(builder);
            wrapper.HiddenProperties.Add("Provider");
            wrapper.HiddenProperties.Add("ConnectionString");
            return wrapper;
        }

        #endregion

        #region IOleDbEditor Members

        public void SetOleProviderID(string invariantName)
        {
            builder.Provider = invariantName;
        }

        #endregion

        #region helper methods

        void cmdFindDatabase_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                SetValue("Data Source", fd.FileName);
                txDataSource.Text = builder.DataSource;
            }
        }

		 void SetValue(string key, object value)
        {
            if (builder.ContainsKey(key))
                builder[key] = value;
        }

        object GetValue(string key)
        {
            if (builder.ContainsKey(key))
                return builder[key];
            return null;
        } 

	    #endregion

    }
}
